//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package event_dao

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/events_api"
	"github.com/golang/protobuf/ptypes/any"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type ProjectEventIndexDbItem struct {
	EventIndexId    string `bson:"_id"`
	ProjectId       string `bson:"projectId"`
	ProjectName     string `bson:"projectName"`
	UserId          string `bson:"userId"`
	UserDisplayName string `bson:"userDisplayName"`
	EventSourceId   string `bson:"eventSourceId"`
	SourceUserName  string `bson:"sourceUserName"`
	EventId         string `bson:"eventId"`
	EventType       uint32 `bson:"eventType"`
	RefType         uint32 `bson:"refType"`
	RefId           string `bson:"refId"`
	EventTime       int64  `bson:"eventTime"`
}

func (item *ProjectEventIndexDbItem) ToEvent(eventData *any.Any, curUserDisplayName, curLogoUri string) *events_api.Event {
	return &events_api.Event{
		EventId:            item.EventId,
		UserId:             item.UserId,
		UserDisplayName:    item.UserDisplayName,
		ProjectId:          item.ProjectId,
		ProjectName:        item.ProjectName,
		EventType:          events_api.EVENT_TYPE(item.EventType),
		EventTime:          item.EventTime,
		RefType:            events_api.EVENT_REF_TYPE(item.RefType),
		RefId:              item.RefId,
		EventData:          eventData,
		CurUserDisplayName: curUserDisplayName,
		CurLogoUri:         curLogoUri,
	}
}

type _ProjectEventIndexDao struct {
	mc *mongo.Collection
}

func newProjectEventIndexDao(db *mongo.Database) (*_ProjectEventIndexDao, error) {
	mc := db.Collection(db_ns.DB_NS_EVENT + "project_index")
	_, err := mc.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys: bson.D{{"projectId", 1}, {"eventTime", 1}},
		},
		{
			Keys: bson.D{{"projectId", 1}, {"refId", 1}, {"eventTime", 1}},
		},
	})
	if err != nil {
		return nil, err
	}
	return &_ProjectEventIndexDao{mc: mc}, nil
}

func (db *_ProjectEventIndexDao) Insert(ctx context.Context, dbItem *ProjectEventIndexDbItem) error {
	dbItem.EventIndexId = db.genEventIndexId(dbItem.ProjectId, dbItem.EventId)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_ProjectEventIndexDao) genEventIndexId(projectId, eventId string) string {
	return fmt.Sprintf("%s:%s", projectId, eventId)
}

func (db *_ProjectEventIndexDao) Count(ctx context.Context, projectId string, filterUserId bool, userId string, filterByTime bool, fromTime, toTime int64, skipCustom bool) (uint32, error) {
	query := bson.M{"projectId": projectId}
	if filterByTime {
		query["eventTime"] = bson.M{"$gte": fromTime, "$lte": toTime}
	}
	if filterUserId {
		query["userId"] = userId
	}
	if skipCustom {
		query["eventType"] = bson.M{"$ne": uint32(events_api.EVENT_TYPE_EVENT_TYPE_CUSTOM)}
	}
	count, err := db.mc.CountDocuments(ctx, query)
	return uint32(count), err
}

func (db *_ProjectEventIndexDao) List(ctx context.Context, projectId string, filterUserId bool, userId string, skipCustom, filterByTime bool, fromTime, toTime, offset, limit int64, reverse bool) ([]*ProjectEventIndexDbItem, error) {
	query := bson.M{"projectId": projectId}
	if filterByTime {
		query["eventTime"] = bson.M{"$gte": fromTime, "$lte": toTime}
	}
	if filterUserId {
		query["userId"] = userId
	}
	if skipCustom {
		query["eventType"] = bson.M{"$ne": uint32(events_api.EVENT_TYPE_EVENT_TYPE_CUSTOM)}
	}
	sort := 1
	if reverse {
		sort = -1
	}
	cursor, err := db.mc.Find(ctx, query, options.Find().SetSort(bson.M{"eventTime": sort}).SetSkip(offset).SetLimit(limit))
	if err != nil {
		return nil, err
	}
	retList := []*ProjectEventIndexDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_ProjectEventIndexDao) ListByRef(ctx context.Context, projectId string, refType events_api.EVENT_REF_TYPE, refId string) ([]*ProjectEventIndexDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"projectId": projectId, "refType": uint32(refType), "refId": refId}, options.Find().SetSort(bson.M{"eventTime": 1}))
	if err != nil {
		return nil, err
	}
	retList := []*ProjectEventIndexDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_ProjectEventIndexDao) Get(ctx context.Context, projectId, eventId string) (*ProjectEventIndexDbItem, error) {
	eventIndexId := db.genEventIndexId(projectId, eventId)
	retItem := &ProjectEventIndexDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": eventIndexId, "projectId": projectId}).Decode(retItem)
	return retItem, err
}

func (db *_ProjectEventIndexDao) ListById(ctx context.Context, projectId string, eventIdList []string) ([]*ProjectEventIndexDbItem, error) {
	eventIndexIdList := []string{}
	for _, eventId := range eventIdList {
		eventIndexId := db.genEventIndexId(projectId, eventId)
		eventIndexIdList = append(eventIndexIdList, eventIndexId)
	}
	cursor, err := db.mc.Find(ctx, bson.M{"projectId": projectId, "_id": bson.M{"$in": eventIndexIdList}})
	if err != nil {
		return nil, err
	}
	retList := []*ProjectEventIndexDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
